package com.tj.jinzao.fragment;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tj.jinzao.R;
import com.tj.jinzao.activity.MyIdentificationLiveActivity;
import com.tj.jinzao.activity.MyIdentificationRealActivity;
import com.tj.jinzao.activity.StartLiveActivity;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseFragment;
import com.tj.jinzao.base.ConstantApp;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.LiveStartBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.utils.DisplayUtil;
import com.tj.jinzao.utils.MessageUtil;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.ChooseTitleWordDialog;

import java.lang.reflect.Field;
import java.util.HashMap;

import butterknife.BindView;
import io.agora.rtc.Constants;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 社区首页
 * Created by wjy on 2018/12/11.
 */
public class LiveFragment extends BaseFragment {

    @BindView(R.id.viewPager)
    ViewPager mViewPaper;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.iv_apply)
    TextView iv_apply;
    private FragmentPagerAdapter mPagerAdapter;
    private int mPrevPosition = -1;
    private Fragment mCurrentFragment;
    private int mPosition = 0;

    public static LiveFragment newInstance() {
        LiveFragment fragment = new LiveFragment();
        Bundle args = new Bundle(1);
        args.putInt(ARG_LAYOUT_RES_ID, R.layout.fragment_live);
        fragment.setArguments(args);
        return fragment;
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(user.getLiveBroadcastApply()!=2){
            iv_apply.setText("申请");
        }else {
            iv_apply.setText("开播");
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(iv_apply!=null){
            addSubscription(mApiService.getUserInfo(UserManager.getInstance().getUser().getId()), new SubscriberCallBack<User>(getActivity()) {
                @Override
                protected void onSuccess(User user) {
                    if(user!=null){
                        UserManager.saveUserData(user);
                    }
                    if(user.getLiveBroadcastApply()!=2){
                        iv_apply.setText("申请");
                    }else {
                        iv_apply.setText("开播");
                    }

                }

                @Override
                protected void onFailure(ResultResponse response) {
                }

                @Override
                protected boolean isShowProgress() {
                    return false;
                }

                @Override
                protected void onPageSuccess(int currentPage, int allPage, int allSize) {
                }
            });

        }

    }

    User user;
    @Override
    protected void setupViews(LayoutInflater inflater, View view) {
        super.setupViews(inflater, view);
        user= UserManager.getInstance().getUser();
        mToolbarTitle.setText("直播");
        setAdapter();
         iv_apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(user.getVerified()!=2){
                    startActivity(new Intent(getActivity(), MyIdentificationRealActivity.class));
                }else {
                    if(user.getLiveBroadcastApply()!=2){
                        startActivity(new Intent(getActivity(), MyIdentificationLiveActivity.class));
                    }else {
                        getStartLive();
                    }

                }


            }
        });
    }
    private ChooseTitleWordDialog mDialog;

    private void getStartLive(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid",UserManager.getInstance().getUser().getId());
        addSubscription(mApiService.getStartLive(hashMap), new SubscriberCallBack<LiveStartBean>(getActivity()) {
            @Override
            protected void onSuccess(LiveStartBean list) {
                Intent i = new Intent(getActivity(), StartLiveActivity.class);
                i.putExtra(ConstantApp.ACTION_KEY_CROLE, Constants.CLIENT_ROLE_BROADCASTER);
                i.putExtra("user", user);
                i.putExtra("bid", list.getLiveId());
                i.putExtra("idlive", list.getId());
                i.putExtra(ConstantApp.ACTION_KEY_ROOM_NAME, String.valueOf(user.getId()));
                i.putExtra(MessageUtil.INTENT_EXTRA_IS_TYPE, false);
                startActivity(i);

            }

            @Override
            protected void onFailure(ResultResponse response) {
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });


    }

    public void setAdapter() {
        mPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(final int position) {
                return LiveListFragment.newInstance(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "关注";
                    case 1:
                        return "推荐";
                    case 2:
                        return "广场";
                    default:
                        return "";
                }
            }

            @Override
            public int getCount() {
                return 3;
            }


            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                if (object == null || (mPrevPosition == position && mCurrentFragment != null))
                    return;
                mPrevPosition = position;
                mCurrentFragment = (Fragment) object;
                if (null == mCurrentFragment) return;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
                getChildFragmentManager().beginTransaction()
                        .remove((Fragment) object).commitAllowingStateLoss();
                try {
                    Field parentFragment = Fragment.class.getDeclaredField("mParentFragment");
                    parentFragment.setAccessible(true);
                    parentFragment.set(object, null);
                } catch (NoSuchFieldException ignored) {
                } catch (IllegalAccessException ignored) {
                }
            }
        };
        mViewPaper.setAdapter(mPagerAdapter);
        mViewPaper.setCurrentItem(mPosition);
        mTabLayout.setupWithViewPager(mViewPaper);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mTabLayout.getLayoutParams();
        params.setMargins(Utils.dpToPx(40,getResources()),0,Utils.dpToPx(40,getResources()),0);
        mTabLayout.setLayoutParams(params);
        View view1= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt1=view1.findViewById(R.id.txt);
        txt1.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        txt1.setText("关注");
        txt1.setTextColor(getResources().getColor(R.color.global_set));
        View view2= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt2=view2.findViewById(R.id.txt);
        txt2.setText("推荐");
        txt2.setTextColor(getResources().getColor(R.color.global_set));
        txt2.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        View view3= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt3=view3.findViewById(R.id.txt);
        txt3.setTextColor(getResources().getColor(R.color.global_set));
        txt3.setText("广场");
        txt3.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        mTabLayout.getTabAt(0).setCustomView(view1);
        mTabLayout.getTabAt(1).setCustomView(view2);
        mTabLayout.getTabAt(2).setCustomView(view3);

    }

    @Override
    public void onStart() {
        super.onStart();
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(mTabLayout, 26, 26);
            }
        });
    }

    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

}